package com.platform.api;

import cn.hutool.core.lang.Validator;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.config.IntegralType;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.platform.config.Constants.SIGNIN_INTEGRAL;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {

    @Autowired
    private ApiUserService userService;

    @Autowired
    private ApiWxFromidService wxFromidService;

    @Autowired
    private ApiSigninRecordService signinRecordService;
    @Autowired
    private ApiUserIntegralService integralService;
    @Autowired
    private ApiSysMacroService macroService;//通用字典表


    /**
     * 用户签到
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("signIn")
    public Object signIn(@LoginUser UserVo loginUser) {

        //todo 判断今天有无签到
        Map<String, Object> params = new HashMap<>();
        params.put("userId", loginUser.getUserId());
        params.put("addDate", new Date());
        List<SigninRecordVo> signinRecordVos = signinRecordService.queryList(params);
        if (signinRecordVos.size() > 0) {
            return toResponsFail("已签到");
        }

        //todo 获取积分
        Integer signinIntegral = SIGNIN_INTEGRAL;
        //签到积分
        SysMacroVo macroVo1 = macroService.queryObject((long) 12);
        if (macroVo1 != null) {
            String value = macroVo1.getValue();
            if (Validator.isNumber(value)) {
                signinIntegral = Integer.valueOf(value);
            }
        }

        UserIntegralVo userIntegralVo = new UserIntegralVo();
        userIntegralVo.setUserId(Integer.valueOf(loginUser.getUserId().toString()));
        //状态:1-增加；2-减少(即使用)
        userIntegralVo.setStatus(1);
        userIntegralVo.setIntegral(signinIntegral);
        IntegralType signUpIntegralType = IntegralType.SIGN_UP_INTEGRAL_TYPE;
        userIntegralVo.setRemark(signUpIntegralType.getName());
        userIntegralVo.setIntegralType(signUpIntegralType.getIndex());
        userIntegralVo.setAddTime(new Date());
        integralService.save(userIntegralVo);

        //汇总用户目前积分
        integralService.calUserCurrentPoints(loginUser.getUserId(), 1, userIntegralVo.getIntegral());

        //todo 记录签到
        SigninRecordVo signinRecordVo = new SigninRecordVo();
        signinRecordVo.setUserId(Integer.valueOf(loginUser.getUserId().toString()));
        signinRecordVo.setUserNickname(loginUser.getNickname());
        signinRecordVo.setRewardIntegral(userIntegralVo.getIntegral().toString());
        signinRecordVo.setAddTime(new Date());
        signinRecordService.save(signinRecordVo);

        return toResponsSuccess("+" + signinIntegral + "积分");


    }

    /**
     * 收集微信小程序中的fromid
     *
     * @param openid
     * @param fromid
     */
    @RequestMapping("addfromid")
    @IgnoreAuth
    public Object addfromid(@RequestParam String openid, @RequestParam String fromid) {

        if (fromid.equals("the formId is a mock one")) {
            return toResponsSuccess("the formId is a mock one");
        }

        WxFromidVo wxFromidVo = new WxFromidVo();
        wxFromidVo.setOpenid(openid);
        wxFromidVo.setFromid(fromid);
        wxFromidVo.setAddTime(new Date());
        wxFromidVo.setIsUsed(0);//是否已经使用：0-未使用；1-已使用
        wxFromidService.save(wxFromidVo);
        return toResponsSuccess(null);
    }

    /**
     * 发送短信
     */
    @RequestMapping("queryUserByPhone")
    public Object queryUserByMobile(@RequestParam String phone) {

        UserVo userVo = userService.queryByMobile(phone);
        if (userVo == null) {
            return toResponsFail("查询不到该手机号码的用户");
        }

        userVo.setPassword("");//和谐掉
        userVo.setWeixin_openid("");//和谐掉

        return toResponsSuccess(userVo);
    }

    /**
     * 发送短信(采用阿里云短信)
     */
    @RequestMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser, @RequestParam String phone) {


        if (!Validator.isMobile(phone)) {
            return toResponsFail("请填写正确的手机号码");
        }

        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(4);
        String msgContent = "您的验证码是：" + sms_code + "，请在页面中提交验证码完成验证。";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", sms_code);
//        Boolean sendCode = ALiSmsUtils.sendCode("春芽健康科技", "SMS_143810054", paramMap, phone);
//
//        if (!sendCode) {
//            return toResponsFail("短信发送失败");
//        }

        smsLogVo = new SmsLogVo();
        smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
        smsLogVo.setUser_id(loginUser.getUserId());
        smsLogVo.setPhone(phone);
        smsLogVo.setSms_code(sms_code);
        smsLogVo.setSms_text(msgContent);
        userService.saveSmsCodeLog(smsLogVo);
        //正式使用短信验证码前，先接口返回真实验证码
        return toResponsSuccess(sms_code);
    }


    /**
     * 获取当前会员的信息
     */
    @RequestMapping("getUserInfo")
    public Object getUserInfo(@LoginUser UserVo loginUser) {

        UserVo userVo = userService.getUserInfo(loginUser.getUserId());
        if (Validator.isNotEmpty(userVo)) {
            if (Validator.isNotEmpty(userVo.getNickname())) {
                userVo.setNickname(EmojiUtils.emojiRecovery2(userVo.getNickname()));
            }
        }
        return toResponsSuccess(userVo);
    }

    /**
     * 修改头像
     */
    @RequestMapping("uploadHeadImg")
    public Object uploadHeadImg(@LoginUser UserVo loginUser, @RequestParam String headImgUrl) {

        UserVo userVo = userService.queryObject(loginUser.getUserId());

        if (userVo == null) {
            return toResponsFail("当前用户不存在");
        }

        userVo.setAvatar(headImgUrl);
        userService.update(userVo);

        return toResponsSuccess(userVo);
    }


    /**
     * 绑定手机号码
     */
    @RequestMapping("bindMobile")
    public Object bindMobile(@LoginUser UserVo loginUser, @RequestParam String mobile_code) {

        //账号若已绑定手机号码，则不支持修改
        if (Validator.isNotEmpty(loginUser.getMobile())) {
            return toResponsFail("当前账号已绑定手机号码，暂不支持修改");
        }

        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());

        if (Validator.isEmpty(smsLogVo)) {
            return toResponsFail("请先获取验证码");
        }

        //有效期5分钟
        if ((System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) > 5 * 60) {
            return toResponsFail("验证码已过期");
        }

        if (!mobile_code.equals(smsLogVo.getSms_code())) {
            return toResponsFail("验证码错误");
        }

        loginUser.setMobile(smsLogVo.getPhone());//获取手机号码

        userService.update(loginUser);

        return toResponsSuccess("手机号码绑定成功");
    }


}